import http from '@/utils/http'
import type { PageQuery, PageRes } from '@/types/api'

const BASE_URL = '/generator/Circulation'

// ==================== 类型定义 ====================

/**
 * 设备周转查询响应接口
 */
export interface DeviceCirculationResp {
  circulationId: string
  deviceName: string
  location: string
  category: number
  taskId: string
  userId: string
  managementId: string
  modelId: string
  factoryId: string
  measureUnit: number
  count: number
  status?: string | number
  nickname: string
  taskname: string
  taskName?: string // 兼容字段，统一使用 taskname
  useTime: string
  backTime: string
  remark?: string
  checkoutDate?: string
  scarpTime: string
}
/**
 * 设备状态更新请求接口
 */
export interface DeviceCirculationStatusUpdateReq {
  circulationId: string | number
  status: number
}

/**
 * 设备周转详情响应接口
 */
export interface DeviceCirculationDetailResp {
  id: string | null
  deviceName: string
  location: string
  category: number
  managementId: string
  modelId: string
  factoryId: string
  measureUnit: number
  count: number
  status?: number
  nickname: string
  taskName: string
  useTime: string
  backTime: string
  remark?: string
  checkoutDate?: string
  scarpTime: string
  createUserString: string
  updateUserString: string
  createTime: string
  updateTime: string | null
}

/**
 * 设备周转信息更新请求接口
 */
export interface DeviceCirculationUpdateReq {
  circulationId: string
  location: string
  status?: number
  useTime: string
  taskId?: string
  userId?: string
  backTime?: string
  scarpTime?: string
  remark?: string
}





/**
 * 设备周转查询条件接口
 */
export interface DeviceCirculationQuery {
  deviceName?: string
  category?: string | number
  modelId?: string
  factoryId?: string
  useTime?: string
  sort?: string[]
}

/**
 * 设备周转分页查询接口
 */
export interface DeviceCirculationPageQuery extends DeviceCirculationQuery, PageQuery {}




/**
 * 通用响应结果接口
 */
export interface Result<T = any> {
  code: string | number
  message?: string  // 后端 Result 类使用的字段名
  data: T
  success: boolean
  timestamp: number
}

/**
 * 用户选项接口
 */
export interface UserOption {
  id: string
  nickname: string
}

/**
 * 任务选项接口
 */
export interface TaskOption {
  id: string
  name: string
}

/**
 * 设备使用登记请求接口
 */
export interface DeviceCirculationRegisterReq {
  circulationId: string
  useTime: string
  location: string
  userId: string
  status?: number
  deviceName: string
  taskId?: string // 可选字段
}




// ==================== API 方法 ====================

/**
 * 使用登记
 */
export function registerDevice(data: DeviceCirculationRegisterReq) {
  return http.put<Result<string>>(`${BASE_URL}/register`, data)
    .then(res => ({
      ...res,
      success: res.success ?? true,
      timestamp: res.timestamp || Date.now()
    }))
    .catch((error: any) => {
      // 如果响应拦截器已经处理了错误，需要从错误对象中提取信息
      const errorMessage = error?.message || error?.response?.data?.message || error?.response?.data?.msg || '登记失败'
      return Promise.reject({
        ...error,
        msg: errorMessage,
        message: errorMessage,
        success: false
      })
    })
}

/**
 * 分页查询设备列表
 */
export function listDeviceCirculation(query: DeviceCirculationPageQuery) {
  return http.post<PageRes<DeviceCirculationResp[]>>(`${BASE_URL}/select`, query)
}

/**
 * 查询设备详情
 */
export function getDeviceCirculationDetail(id: string) {
  return http.post<Result<DeviceCirculationDetailResp>>(`${BASE_URL}/detail/${id}`)
    .then(res => {
      if (res.success && res.data) {
        return { data: res.data }
      }
      throw new Error(res.msg || res.data.message || '获取设备详情失败')
    })
}

/**
 * 搜索用户
 */
export function searchUsers() {
  return http.get<Result<UserOption[]>>(`/system/user/searchAny`)
    .then(res => {
      if (res.success && res.data) {
        // 处理嵌套的 data 结构
        return Array.isArray(res.data) ? res.data : (res.data.data || [])
      }
      throw new Error(res.msg || res.data.message || '搜索用户失败')
    })
    .catch(error => {
      console.error('搜索用户失败:', error)
      throw error
    })
}

/**
 * 更新设备状态
 */
export function updateDeviceStatus(data: DeviceCirculationStatusUpdateReq) {
  return http.put<Result<string>>(`${BASE_URL}/updateStatus`, data)
    .then(res => ({
      ...res,
      success: res.success ?? true,
      timestamp: res.timestamp || Date.now()
    }))
    .catch((error: any) => {
      // 如果响应拦截器已经处理了错误，需要从错误对象中提取信息
      const errorMessage = error?.message || error?.response?.data?.message || error?.response?.data?.msg || '状态修改失败'
      return Promise.reject({
        ...error,
        msg: errorMessage,
        message: errorMessage,
        success: false
      })
    })
}



/**
 * 搜索任务
 */
export function searchTasks() {
  return http.get<Result<TaskOption[]>>(`/task/info/searchAny`)
    .then(res => {
      if (res.success && res.data) {
        // 处理嵌套的 data 结构
        return Array.isArray(res.data) ? res.data : (res.data.data || [])
      }
      throw new Error(res.msg || res.data.message || '搜索任务失败')
    })
    .catch(error => {
      console.error('搜索任务失败:', error)
      throw error
    })
}

/**
 * 更新设备流转信息
 */
export function updateDeviceCirculation(data: DeviceCirculationUpdateReq) {
  return http.put<Result<string>>(`${BASE_URL}/updateById`, data)
}

/**
 * 删除设备流转信息
 * @param ids 设备ID数组或逗号分隔的ID字符串
 */
export function deleteDeviceCirculation(ids: string[] | string) {
  const idParam = Array.isArray(ids) ? ids.join(',') : ids
  return http.del<Result<string>>(`${BASE_URL}/${idParam}`)
}

/**
 * 导出设备数据
 */
export function exportDeviceCirculation(query: DeviceCirculationQuery) {
  return http.download(`${BASE_URL}/export`, { params: query })
}

/**
 * 归还设备
 */
export function returnDevice(id: string) {
  return http.put<Result<string>>(`${BASE_URL}/return/${id}`)
    .then(res => ({
      ...res,
      success: res.success ?? true,
      timestamp: res.timestamp || Date.now()
    }))
}

/**
 * 设备登记记录响应接口
 */
export interface DeviceRegisterRecordResp {
  id: string | number
  deviceName: string
  cirId: string | number
  userId: string | number
  userName?: string
  optId: string | number
  operatorName?: string
  registerDate: string
  locId?: string | number
  locationId?: string | number
  locationName?: string
  createUser: string | number
  createTime: string
  updateUser?: string | number
  updateTime?: string
}

/**
 * 查询设备登记记录请求接口
 */
export interface DeviceRegisterRecordQuery {
  circulationId: string
}

/**
 * 查询设备登记记录列表
 */
export function listDeviceRegisterRecords(circulationId: string) {
  return http.get<Result<DeviceRegisterRecordResp[]>>(`${BASE_URL}/registerRecords/${circulationId}`)
    .then(res => {
      // res 是 axios response 对象，res.data 是 Result 对象
      const result = res.data
      return {
        success: result.success ?? true,
        data: result.data,
        msg: result.message || result.msg,
        message: result.message,
        code: result.code,
        timestamp: result.timestamp || Date.now()
      }
    })
}

/**
 * 导出设备登记记录
 */
export function exportDeviceRegisterRecords(circulationId: string) {
  return http.download(`${BASE_URL}/exportRegisterRecords/${circulationId}`)
}

/**
 * 导出即将到期设备清单
 */
export function exportExpiringDeviceCirculation(query: DeviceCirculationQuery) {
  return http.download(`${BASE_URL}/export/expiring`, { params: query })
}
